﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Benefit.Models.Sys;
using Benefit.Models.Year;
using System.Data.Entity;
namespace Benefit.Service.Year
{
    public class ServiceBrokerageYearTradeInfo : Benefit.Interface.Year.IBrokerageYearTradeInfo
    {
        Benefit.DB.DBManager db = null;
        public ServiceBrokerageYearTradeInfo(Benefit.DB.DBManager db)
        {
            this.db = db;
        }
        /// <summary>
        /// 删除当月所有记录
        /// </summary>
        /// <param name="tradeHistoryId"></param>
        public void Delete(int year)
        {
            var query = from t in db.BrokerageYearTradeInfo where t.Year == year select t;
            foreach (BrokerageYearTradeInfo d in query)
            {
                db.BrokerageYearTradeInfo.Remove(d);
            }
            db.SaveChanges();
        }


        /// <summary>
        /// 初始化经纪公司月收益情况
        /// </summary>
        /// <param name="month"></param>
        /// <param name="year"></param>
        public void InitBrokerYearTradeInfo(int year)
        {
            BrokerageYearTradeInfo binfo = new BrokerageYearTradeInfo();
            var query = db.BrokerageMonthTradeInfo.Where(a => a.Year == year);
            var query2 = db.BrokerageYearTradeInfo.Where(a => a.Year == year);
            if (query2.Count() > 0)
            {
                binfo = query2.First();
            }
            binfo.BillCount = query.Sum(a => a.BillCount);
            binfo.BrokerId = query.First().BrokerId;
            binfo.DayCount = query.Sum(a => a.DayCount);
            binfo.Free = query.Sum(a => a.Free);
            binfo.LoseCount = query.Sum(a => a.LoseCount);
            binfo.Profit = query.Sum(a => a.Profit);
            binfo.SumLost = query.Sum(a => a.SumLost);
            binfo.SumWin = query.Sum(a => a.SumWin);
            binfo.UsedMargin = query.Sum(a => a.UsedMargin);
            binfo.WinCount = query.Sum(a => a.WinCount);
            binfo.Year = year;
            if (query2.Count() == 0)
            {
                db.BrokerageYearTradeInfo.Add(binfo);
            }
            db.SaveChanges();
        }

        public List<BrokerageYearTradeInfo> GetBrokerageYearTradeInfo(int brokerid, int year)
        {
            var query = db.BrokerageYearTradeInfo.Where(a => a.BrokerId == brokerid).Where(a => a.Year == year).Include(a => a.Broker);
            return query.ToList();
        }

        public List<BrokerageYearTradeInfo> GetBrokerageYearTradeInfo(int year)
        {
            var query = db.BrokerageYearTradeInfo.Where(a => a.Year == year).Include(a => a.Broker);
            return query.ToList();
        }
    }
}
